﻿using UnityEngine;
using System.Collections;
using System.Threading;
using System.Runtime.InteropServices;
using System.Text;
using System;

public class umsp : MonoBehaviour {
    public int x;
    public int y;
    public partial class NativeConstants {

        /// __UMSP_H__ -> 
        /// Error generating expression: 值不能为空。
        ///参数名: node
        public const string @__UMSP_H__ = "";

        /// EXPORT -> __declspec(dllexport)
        /// Error generating expression: Error generating function call.  Operation not implemented
        public const string EXPORT = "__declspec(dllexport)";

        /// FUNC_CALL_TYPE -> __stdcall
        /// Error generating expression: Value __stdcall is not resolved
        public const string FUNC_CALL_TYPE = "__stdcall";
    }
    [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential, CharSet = System.Runtime.InteropServices.CharSet.Ansi)]
    public struct Packet {

        /// int
        public int size;

        /// char[2048]
        [System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.ByValArray, SizeConst = 2048)]
        public byte[] buf;
    }
    /// Return Type: void
    ///packet: void*
    [System.Runtime.InteropServices.UnmanagedFunctionPointerAttribute(System.Runtime.InteropServices.CallingConvention.StdCall)]
    public delegate void Dispatcher(System.IntPtr packet);


    public partial class NativeMethods {

        /// Return Type: int
        ///buf: char*
        ///bufLen: int
        [System.Runtime.InteropServices.DllImportAttribute("umsp", EntryPoint = "UMSP_sendMessage", CallingConvention = System.Runtime.InteropServices.CallingConvention.StdCall)]
        public static extern int UMSP_sendMessage(byte[] buf, int bufLen);


        /// Return Type: int
        ///HOST: char*
        ///PORT: int
        [System.Runtime.InteropServices.DllImportAttribute("umsp", EntryPoint = "UMSP_init", CallingConvention = System.Runtime.InteropServices.CallingConvention.StdCall)]
        public static extern int UMSP_init(byte[] HOST, int PORT);


        /// Return Type: int
        ///handler: void*
        [System.Runtime.InteropServices.DllImportAttribute("umsp", EntryPoint = "UMSP_setPacketHandler", CallingConvention = System.Runtime.InteropServices.CallingConvention.StdCall)]
        public static extern int UMSP_setPacketHandler(Dispatcher handler);


        /// Return Type: int
        [System.Runtime.InteropServices.DllImportAttribute("umsp", EntryPoint = "UMSP_uninit", CallingConvention = System.Runtime.InteropServices.CallingConvention.StdCall)]
        public static extern int UMSP_uninit();


        /// Return Type: int
        [System.Runtime.InteropServices.DllImportAttribute("umsp", EntryPoint = "UMSP_getNetWorkState", CallingConvention = System.Runtime.InteropServices.CallingConvention.StdCall)]
        public static extern int UMSP_getNetWorkState();

    }



    public static  void onRecvPacket(IntPtr packet) {
        var p = (Packet)Marshal.PtrToStructure(packet, typeof(Packet));
        Debug.Log("onRecvPacket size:" + p.size);
        if(p.size > 24) {
            byte[] dest = new byte[p.size];
            Buffer.BlockCopy(p.buf, 24, dest, 0, p.size-24);
            System.String msg = Encoding.UTF8.GetString(dest);
           
            Loom.QueueOnMainThread(()=>{
                onRecvJSON(msg);
            });
        }
    }
    public static void run() {
        Debug.Log("run start");
        NativeMethods.UMSP_setPacketHandler(onRecvPacket);
        NativeMethods.UMSP_init(System.Text.Encoding.ASCII.GetBytes("192.168.8.155"), 12345);
        Debug.Log("run over");
    }
    /// <summary>
    /// 接收到一个来自网络的json消息
    /// </summary>
    /// <param name="json"></param>
    public static void onRecvJSON(string json) {
        Debug.Log("onRecvString" + json);
    }

    // Use this for initialization
    void Start() {
        Thread t = new Thread(run);
        t.Start();
        Debug.Log("Start"+System.DateTime.Now);
    }
    int netWorkState = 0;
    // Update is called once per frame
    void Update() {

        netWorkState = NativeMethods.UMSP_getNetWorkState();
        if(netWorkState == 1) {
            byte[] msg = Encoding.ASCII.GetBytes("hello");
            NativeMethods.UMSP_sendMessage(msg, msg.Length);
            Debug.Log("sendMessage:"+ msg);
        }
        else if(netWorkState == 2) {
            //disconnect
        } else if(netWorkState == 3) {
            //shutdown
        } else {
            //connecting
        }
    }
    void OnDestroy() {
        print("Script was destroyed");
        NativeMethods.UMSP_uninit();
        Debug.Log("OnDestory UMSP_getNetWorkState:" + NativeMethods.UMSP_getNetWorkState());
    }
}
